package main

import (
	"crypto/tls"
	"crypto/x509"
	"encoding/json"
	"fmt"
	"github.com/eclipse/paho.mqtt.golang"
	"log"
	"os"
)

func main() {
	CfgInit()
}

func connectMQTT() mqtt.Client {
	// TLS 配置
	tlsConfig := createTLSConfig()

	// 连接选项
	opts := mqtt.NewClientOptions()
	opts.AddBroker("tls://mqtt.example.com:8883") // TLS 端口
	opts.SetClientID("go-mqtt-client-001")
	opts.SetUsername("username")
	opts.SetPassword("password")
	opts.SetTLSConfig(tlsConfig)

	// 连接回调
	opts.OnConnect = func(c mqtt.Client) {
		log.Println("成功连接MQTT代理")

		// 订阅主题
		token := c.Subscribe("devices/+/status", 1, onMessageReceived)
		token.Wait()
		log.Printf("已订阅主题 devices/+/status")
	}

	opts.OnConnectionLost = func(c mqtt.Client, err error) {
		log.Printf("连接丢失: %v", err)
	}

	// 创建并连接客户端
	client := mqtt.NewClient(opts)
	if token := client.Connect(); token.Wait() && token.Error() != nil {
		panic(fmt.Sprintf("连接失败: %v", token.Error()))
	}

	return client
}

func createTLSConfig() *tls.Config {
	// 1. 加载 CA 证书 (验证服务端)
	caCert, _ := os.ReadFile("certs/ca.crt")
	caCertPool := x509.NewCertPool()
	caCertPool.AppendCertsFromPEM(caCert)

	// 2. 加载客户端证书 (双向认证)
	cert, _ := tls.LoadX509KeyPair("certs/client.crt", "certs/client.key")

	return &tls.Config{
		RootCAs:            caCertPool,              // 验证服务端证书
		Certificates:       []tls.Certificate{cert}, // 客户端证书
		InsecureSkipVerify: false,                   // 必须验证证书
		MinVersion:         tls.VersionTLS12,        // 强制 TLS 1.2+
	}
}

// 消息接收处理
func onMessageReceived(c mqtt.Client, msg mqtt.Message) {
	log.Printf("收到消息 [%s]: %s\n", msg.Topic(), msg.Payload())

	// 解析JSON等处理
	var data map[string]interface{}
	if err := json.Unmarshal(msg.Payload(), &data); err == nil {
		log.Printf("设备ID: %s, 状态: %s", data["device_id"], data["status"])
	}
}
